package com.zhongxi.guoyuan.view.rewardCoin;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.shopcart.AddressListData;
import com.zhongxi.guoyuan.entity.shopcart.City;
import com.zhongxi.guoyuan.entity.shopcart.CityData;
import com.zhongxi.guoyuan.entity.shopcart.Prefecture;
import com.zhongxi.guoyuan.entity.shopcart.PrefectureData;
import com.zhongxi.guoyuan.entity.shopcart.Province;
import com.zhongxi.guoyuan.entity.shopcart.ProvinceData;
import com.zhongxi.guoyuan.url.Url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/22.
 */

public class RewardEditAddressActivity extends BaseActivity implements View.OnClickListener {
    public static final int RESULTADDRESSCODE = 100;
    private TextView tvSubmit;
    private ImageView ivSelect;
    private boolean isSelect;
    private String type;
    private int addressPos = 0;
    private int cityPos = 0;
    private int prefPos = 0;

    private boolean refresh;
    private Map<String, String> map = new HashMap<String, String>();

    private EditText etUserName;
    private EditText etPhone;
    private EditText etAddress;
    private String pid;
    private String cid;
    private String pre;
    private AddressListData data;

    private TextView tv_province;
    private TextView tv_city;
    private TextView tv_prefecture;

    private List<ProvinceData> provinceData;
    private List<CityData> cityData;
    private List<PrefectureData> prefectureData;
    private boolean isShow;
    private boolean isPrefectureData;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_edit_address);
        initTitle();
        tvTitle.setText("添加地址");
        tvSubmit = (TextView) findViewById(R.id.tvSubmit);
        ivSelect = (ImageView) findViewById(R.id.ivSelect);
        etUserName = (EditText) findViewById(R.id.etUserName);
        etPhone = (EditText) findViewById(R.id.etPhone);
        etAddress = (EditText) findViewById(R.id.etAddress);
        tv_province = (TextView) findViewById(R.id.tv_province);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_prefecture = (TextView) findViewById(R.id.tv_prefecture);
    }

    @Override
    protected void initData() {
        super.initData();
        data = (AddressListData) getIntent().getSerializableExtra("data");
        if (null != data && !"".equals(data)) {
            tvTitle.setText("编辑地址");
            if (null != data.getUsername() && !"".equals(data.getUsername())) {
                etUserName.setText(data.getUsername());
            }
            if (null != data.getMphone() && !"".equals(data.getMphone())) {
                etPhone.setText(data.getMphone());
            }
            if (null != data.getAddress() && !"".equals(data.getAddress())) {
                etAddress.setText(data.getAddress());
            }
            if (null != data.getPid() && !"".equals(data.getPid())) {
                pid = data.getPid();
            }
            if (null != data.getCid() && !"".equals(data.getCid())) {
                cid = data.getCid();
            }
            if (null != data.getPreid() && !"".equals(data.getPreid())) {
                pre = data.getPreid();
            }
            if (!TextUtils.isEmpty(data.getProvince())) {
                tv_province.setText(data.getProvince());
            }
            if (!TextUtils.isEmpty(data.getCity())) {
                tv_city.setText(data.getCity());
            }
            if (!TextUtils.isEmpty(data.getPrefecture())) {
                tv_prefecture.setText(data.getPrefecture());
            }
        }
    }

    /**
     * 获取省份列表
     */
    private void getProvince() {
        type = "province";
        getServer(Url.REWARD_PROVINCE_LIST, null, "", false, null, "get");
    }

    /**
     * 获取城市列表
     */

    private void getCity() {
        type = "city";
        String str = "";
        if (data != null && !"".equals(data)) {
            if (data.getProvince().equals(tv_province.getText().toString().trim())) {
                str = "&pid=" + pid;
            } else {
                str = "&pid=" + provinceData.get(addressPos).getP_id();
            }
        } else {
            str = "&pid=" + provinceData.get(addressPos).getP_id();
        }
        getServer(Url.REWARD_CITY_LIST, null, str, false, null, "get");
    }

    /**
     * 获取区县列表
     */

    private void getPrefecture() {
        type = "prefecture";
        String str = "";
        if (data != null && !"".equals(data)) {
            if (data.getProvince().equals(tv_province.getText().toString().trim()) && data.getCity().equals(tv_city.getText().toString().trim())) {
                str = "&pid=" + pid + "&cid=" + cid;
            } else if (data.getProvince().equals(tv_province.getText().toString().trim()) && !data.getCity().equals(tv_city.getText().toString().trim())) {
                str = "&pid=" + pid + "&cid=" + cityData.get(cityPos).getC_id();
            } else {
                str = "&pid=" + provinceData.get(addressPos).getP_id() + "&cid=" + cityData.get(cityPos).getC_id();
            }
        } else {
            str = "&pid=" + provinceData.get(addressPos).getP_id() + "&cid=" + cityData.get(cityPos).getC_id();
        }
        getServer(Url.REWARD_PREFECTURE_LIST, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        ivSelect.setOnClickListener(this);
        tv_province.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_prefecture.setOnClickListener(this);
        tvSubmit.setOnClickListener(this);
    }

    /**
     * 编辑地址
     */
    private void editAddress() {
        type = "edit";
        map.clear();
        map.put("aid", data.getId());
        map.put("username", etUserName.getText().toString().trim());
        map.put("mphone", etPhone.getText().toString().trim());
        if (tv_province.getText().toString().trim().equals(data.getProvince())) {
            map.put("pid", data.getPid());
            map.put("province", data.getProvince());
        } else {
            map.put("pid", provinceData.get(addressPos).getP_id());
            map.put("province", provinceData.get(addressPos).getProvince());
        }
        if (tv_city.getText().toString().trim().equals(data.getCity())) {
            map.put("cid", data.getCid());
            map.put("city", data.getCity());
        } else {
            map.put("cid", cityData.get(cityPos).getC_id());
            map.put("city", cityData.get(cityPos).getCity());
        }
        if (tv_prefecture.getText().toString().trim().equals(data.getPrefecture())) {
            map.put("preid", data.getPreid());
            map.put("prefecture", data.getPrefecture());
        } else {
            map.put("preid", prefectureData.get(prefPos).getPre_id());
            map.put("prefecture", prefectureData.get(prefPos).getPrefecture());
        }
        map.put("address", etAddress.getText().toString().trim());
        getServer(Url.REWARD_EDIT_ADDRESS, map, "", false, null, "post");   //user/editshippingaddress
    }

    /**
     * 增加地址
     */
    private void addAddress() {
        type = "addaddress";
        map.clear();
        map.put("username", etUserName.getText().toString().trim());
        map.put("mphone", etPhone.getText().toString().trim());
        map.put("pid", provinceData.get(addressPos).getP_id());
        map.put("province", provinceData.get(addressPos).getProvince());
        map.put("cid", cityData.get(cityPos).getC_id());
        map.put("city", cityData.get(cityPos).getCity());
        map.put("preid", prefectureData.get(prefPos).getPre_id());
        map.put("prefecture", prefectureData.get(prefPos).getPrefecture());
        map.put("address", etAddress.getText().toString().trim());
        getServer(Url.REWARD_Add_Address, map, "", false, null, "post");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivSelect:
                isSelect = !isSelect;
                if (isSelect) {
                    ivSelect.setImageResource(R.mipmap.yes);
                } else {
                    ivSelect.setImageResource(R.mipmap.no);
                }
                break;
            case R.id.tv_province:
                //判断输入法的隐藏状态
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
                getProvince();
                break;
            case R.id.tv_city:
                if (data != null && !"".equals(data)) {
                    getCity();
                } else {
                    if (provinceData != null && provinceData.size() > 0) {
                        getCity();
                    } else {
                        showShortToast("请先选择 省份");
                    }
                }
                break;
            case R.id.tv_prefecture:
                if (data != null && !"".equals(data)) {
                    if (!data.getProvince().equals(tv_province.getText().toString().trim())
                            && data.getCity().equals(tv_city.getText().toString().trim())) {
                        showShortToast("请先选择 市");
                    } else {
                        getPrefecture();
                    }
                } else {
                    if (provinceData != null && provinceData.size() > 0 && cityData != null && cityData.size() > 0) {
                        getPrefecture();
                    } else {
                        showShortToast("请先选择 省 和 市");
                    }
                }
                break;
            case R.id.tvSubmit:    //新增配送地址
                if (TextUtils.isEmpty(etUserName.getText().toString().trim())) {
                    showShortToast("请输入您的姓名");
                } else if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                    showShortToast("请输入您的手机号！");
                } else if (TextUtils.isEmpty(tv_province.getText().toString().trim()) ||
                        TextUtils.isEmpty(tv_city.getText().toString().trim()) || TextUtils.isEmpty(tv_prefecture.getText().toString().trim())) {
                    showShortToast("请您选择完整的省、市、区/县三级地址");
                } else if (TextUtils.isEmpty(etAddress.getText().toString().trim())) {
                    showShortToast("请输入您的具体地址");
                } else {
                    if (data != null && !"".equals(data)) {
                        editAddress();     //编辑地址
                    } else {
                        addAddress();
                    }
                }
                break;
        }
    }

    private void showProvinceDialog(final List<String> list, final int flag, int pos) {
        final AlertDialog.Builder adb = new AlertDialog.Builder(context);
        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.dialog_view, null);
        adb.setView(view);
        TextView tvNo = (TextView) view.findViewById(R.id.tv_no);
        TextView tvYes = (TextView) view.findViewById(R.id.tv_yes);
        LoopView loopView = (LoopView) view.findViewById(R.id.loopView);
        loopView.setItems(list);
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                switch (flag) {
                    case 1:
                        addressPos = index;
                        break;
                    case 2:
                        cityPos = index;
                        break;
                    case 3:
                        prefPos = index;
                        break;
                }
            }
        });
        loopView.setNotLoop();  //停止无线轮播
        loopView.setInitPosition(pos);
        final AlertDialog alertDialog = adb.create();
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        tvYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                switch (flag) {
                    case 1:
                        tv_province.setText(list.get(addressPos));
                        break;
                    case 2:
                        tv_city.setText(list.get(cityPos));
                        break;
                    case 3:
                        tv_prefecture.setText(list.get(prefPos));
                        break;
                }
            }
        });
        alertDialog.show();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("province".equals(type)) {
                Province province = gson.fromJson(response, Province.class);
                if (null != province.getSafeobj() && !"".equals(province.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(province.getSafeobj());
                }
                List<String> provinceList = new ArrayList<>();
                if (province.getData() != null && province.getData().size() > 0) {
                    provinceData = province.getData();
                    for (int i = 0; i < provinceData.size(); i++) {
                        provinceList.add(provinceData.get(i).getProvince());
                    }
                    if (data != null && !"".equals(data)) {
                        tv_city.setText("");
                        tv_prefecture.setText("");
                        for (int i = 0; i < province.getData().size(); i++) {
                            if (data.getPid().equals(province.getData().get(i).getP_id())) {
                                showProvinceDialog(provinceList, 1, i);
                            }
                        }
                    } else {
                        showProvinceDialog(provinceList, 1, 0);
                    }
                } else {
                    showShortToast("赞无数据");
                }
            } else if ("city".equals(type)) {
                City city = gson.fromJson(response, City.class);
                if (null != city.getSafeobj() && !"".equals(city.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(city.getSafeobj());
                }
                List<String> cityList = new ArrayList<>();
                if (city.getData() != null && city.getData().size() > 0) {
                    cityData = city.getData();
                    for (int i = 0; i < cityData.size(); i++) {
                        cityList.add(cityData.get(i).getCity());
                    }
                    if (data != null && !"".equals(data)) {
                        tv_prefecture.setText("");
                        for (int i = 0; i < cityData.size(); i++) {
                            if (data.getCid().equals(cityData.get(i).getC_id())) {
                                showProvinceDialog(cityList, 2, i);
                                isShow = true;
                            }
                        }
                        if (!isShow) {
                            showProvinceDialog(cityList, 2, 0);
                        }
                    } else {
                        showProvinceDialog(cityList, 2, 0);
                    }
                } else {
                    showShortToast("赞无数据");
                }
            } else if ("prefecture".equals(type)) {
                Prefecture prefecture = gson.fromJson(response, Prefecture.class);
                if (null != prefecture.getSafeobj() && !"".equals(prefecture.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(prefecture.getSafeobj());
                }
                List<String> prefectureList = new ArrayList<>();
                if (prefecture.getData() != null && prefecture.getData().size() > 0) {
                    prefectureData = prefecture.getData();
                    for (int i = 0; i < prefectureData.size(); i++) {
                        prefectureList.add(prefectureData.get(i).getPrefecture());
                    }
                    if (data != null && !"".equals(data)) {
                        for (int i = 0; i < prefectureData.size(); i++) {
                            if (data.getPreid().equals(prefectureData.get(i).getPre_id())) {
                                showProvinceDialog(prefectureList, 3, i);
                                isPrefectureData = true;
                            }
                        }
                        if (!isPrefectureData) {
                            showProvinceDialog(prefectureList, 3, 0);
                        }
                    } else {
                        showProvinceDialog(prefectureList, 3, 0);
                    }
                } else {
                    showShortToast("赞无数据");
                }
            } else if ("addaddress".equals(type)) {
                BaseResponse addResult = gson.fromJson(response, BaseResponse.class);
                if (null != addResult.getSafeobj() && !"".equals(addResult.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(addResult.getSafeobj());
                }
                showShortToast("添加地址成功");
                if (isSelect) {
                    Intent intent = new Intent();
                    intent.putExtra("addressId", addResult.getId());
                    setResult(RESULTADDRESSCODE, intent);
                }
                finish();
            } else if ("edit".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("编辑地址成功");
                if (isSelect) {
                    Intent intent = new Intent();
                    intent.putExtra("addressId", result.getId());
                    setResult(RESULTADDRESSCODE, intent);
                }
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse response1 = gson.fromJson(response, BaseResponse.class);
            if (null != response1 && !"".equals(response1)) {
                MyApplication.getInstance().setSpValue(response1.getSafeobj());
            }
            if (2201 == response1.getCode()) {
                showShortToast("编辑地址失败");
            } else if (1557 == response1.getCode()) {
                showShortToast("收货地址超限");
            } else if (1666 == response1.getCode()) {
                showShortToast("服务不可用，服务器异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
